package com.woniuxy.secondkill.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class KillController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private Redisson redisson;

    @RequestMapping("/kill")
    public boolean kill() {
        //尽量不要使用关键词作为key
        String key = "key";
        //获取锁
        RLock lock = redisson.getLock(key);
        try {
            //加锁
            lock.lock();
            int store = (Integer)redisTemplate.opsForValue().get("store");
            if (store>0){
                store--;
                redisTemplate.opsForValue().set("store",store);
                System.out.println("store还有："+store);
                return true;
            }
        }finally {
            //解锁
            lock.unlock();
        }
        return false;
    }
}
